#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/opt/coopip/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import CIS, AMR, OMS, GIS
from django.contrib.gis.db import models
#********************Setup psycopg2 and django section********************
from django.db import transaction

import urllib
import httplib
import datetime
import csv
from COOPIP_Misc import ConvertCISDisconnectDate


OutputFileName='/home/technology/Desktop/BillingProjectReport.csv'

ColumnHeadings = ["MemberSep", "Previous Read Date", "Read Date", "Bill Date",
                  "Bill Amount Except Energy", "Energy Amount", "Meter #", "Meter Total", "KWH", 'Calculated KWH', 
                  "AMR KWH", "KWH Difference Between AMR and UPN"]
Rows = []
Rows.append(ColumnHeadings)
#Bills=list(CIS.Billhistdetl.objects.filter(mbrsep='00000079002').filter(billmoyr__gte='1301').order_by('billmoyr'))
#Mbrhistdetls=list(CIS.Mbrhistdetl.objects.filter(mbrsep='00000079002').filter(billdate__gte='1301').order_by('billdate'))
Mbrhistdetls=list(CIS.Mbrhistdetl.objects.filter(billdate__gte='1301').order_by('billdate'))
MemberSepMeterLookupDict={}
MemberSepReadDateLookupDict={}  #Previous Read Date and Reading for the specified membersep




def CalculateAMRKWHTotal(COOPIPMeterRead, PreviousReadDate, CurrentReadDate):

    if(PreviousReadDate > CurrentReadDate):
        pass
    KWHUsageDict = COOPIPMeterRead[0].GetKWHUsageDict()
    DatesNeeded = []
    CurrentDate = PreviousReadDate
    while(CurrentDate <= CurrentReadDate):
        DatesNeeded.append(COOPIPMeterRead[0].DateTimeToKey(CurrentDate))
        CurrentDate = CurrentDate + datetime.timedelta(days=1)
    Total = 0
    for i in DatesNeeded:
        if(KWHUsageDict.has_key(i)):
            Total = Total + KWHUsageDict[i]
    return Total



for mbrhistdetl in Mbrhistdetls:
    if(not mbrhistdetl.mbrsep.lstrip('0') in MemberSepReadDateLookupDict):
        MemberSepReadDateLookupDict[mbrhistdetl.mbrsep.lstrip('0')] = [mbrhistdetl.readdate, mbrhistdetl.meterread]
        continue
    row = []
    row.append(mbrhistdetl.mbrsep.lstrip('0'))
    
    #FIXME Find the previous read date from a previous bill
    row.append(ConvertCISDisconnectDate(MemberSepReadDateLookupDict[mbrhistdetl.mbrsep.lstrip('0')][0]))
    row.append(ConvertCISDisconnectDate(mbrhistdetl.readdate))
    row.append(ConvertCISDisconnectDate(mbrhistdetl.billdate))
    PreviousRead = MemberSepReadDateLookupDict[mbrhistdetl.mbrsep.lstrip('0')][1]
    PreviousReadDate = MemberSepReadDateLookupDict[mbrhistdetl.mbrsep.lstrip('0')][0]
    MemberSepReadDateLookupDict[mbrhistdetl.mbrsep.lstrip('0')] = [mbrhistdetl.readdate, mbrhistdetl.meterread]

    row.append(mbrhistdetl.fuel + mbrhistdetl.miscchg + mbrhistdetl.weather + mbrhistdetl.tax +
               mbrhistdetl.localtax + mbrhistdetl.penalty + mbrhistdetl.mbrfee + mbrhistdetl.consdep + mbrhistdetl.otherdep +
               mbrhistdetl.otherchg + mbrhistdetl.interest + mbrhistdetl.equipment +
               mbrhistdetl.arrears + mbrhistdetl.franchisetax + mbrhistdetl.grosstax + mbrhistdetl.othertax + mbrhistdetl.roundup +
               mbrhistdetl.otheramt1 + mbrhistdetl.otheramt2 + mbrhistdetl.otheramt3)
    row.append(mbrhistdetl.energy)

    if(not MemberSepMeterLookupDict.has_key(mbrhistdetl.mbrsep)):
        meterDetl = CIS.Meterdetl.objects.filter(mbrsep=mbrhistdetl.mbrsep).filter(idlecode='00')
        if(meterDetl and len(meterDetl) == 1):
            MemberSepMeterLookupDict[mbrhistdetl.mbrsep] = str(meterDetl[0].meter).lstrip('0')
        else:  #FIXME, cases not handled include meter changes, check Meterhistdetl after partially working
            MemberSepMeterLookupDict[mbrhistdetl.mbrsep] = 'UKNOWN'
    MeterNumber = MemberSepMeterLookupDict[mbrhistdetl.mbrsep]
    row.append(MeterNumber)
    row.append(mbrhistdetl.meterread)
    row.append(mbrhistdetl.kwh)
    row.append(int(mbrhistdetl.meterread) - int(PreviousRead))
    COOPIPMeter = Meter.objects.filter(SerialNumber=MeterNumber)
    if(COOPIPMeter and len(COOPIPMeter) == 1):
        COOPIPMeter = COOPIPMeter[0]
    else:
        row.append('N/A')
        row.append('N/A')  #No AMR Readings Available
        Rows.append(row)
        continue
 
    COOPIPMeterRead = MeterRead.objects.filter(Meter=COOPIPMeter)
    if(not COOPIPMeterRead):
        row.append('N/A')
        row.append('N/A')  #No AMR Readings Available
        Rows.append(row)
        continue

    AMRMeterRead=CalculateAMRKWHTotal(COOPIPMeterRead, ConvertCISDisconnectDate(PreviousReadDate),
                                      ConvertCISDisconnectDate(mbrhistdetl.readdate))
    row.append(AMRMeterRead)
    if(not AMRMeterRead == 'N/A' and mbrhistdetl.meterread):
        row.append(int(AMRMeterRead) - (int(mbrhistdetl.meterread) - int(PreviousRead)))
    else:
        row.append('N/A')
    Rows.append(row)
    


OutputFile = open(OutputFileName, 'wb')
CSVWriter = csv.writer(OutputFile)
for row in Rows:
    CSVWriter.writerow(row)
OutputFile.close()


